package com.coocaa.x.service.liteccconnecter;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.RemoteException;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.CoocaaVersion;
import com.coocaa.x.framework.app.CoocaaService.AIDLInterface;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.ShellUtils;
import com.coocaa.x.framework.utils.ShellUtils.CommandResult;
import com.coocaa.x.service.liteccconnector.LiteCCConnector;
import com.coocaa.x.service.liteccconnector.aidl.ILiteCCConnectorHandler;
import com.coocaa.x.service.liteccconnector.aidl.ILiteCCConnectorService;
import com.skyworth.deservice.DEDefine;
import com.skyworth.framework.skycommondefine.SkyworthBroadcastKey;
import com.skyworth.framework.skycommondefine.SkyworthKeyMap.SkyworthKey;
import com.skyworth.framework.skysdk.android.CoocaaOSTypeChecker;
import com.skyworth.framework.skysdk.ipc.SkyApplication;
import com.skyworth.framework.skysdk.ipc.SkyApplication.SkyCmdConnectorListener;
import com.skyworth.framework.skysdk.ipc.SkyCmdProcessInstance;
import com.skyworth.framework.skysdk.ipc.SkyCmdProcessInstance.SkyCmdProcessInstanceListener;
import com.skyworth.framework.skysdk.ipc.SkyCmdURI;
import com.skyworth.framework.skysdk.util.SkyData;
import com.tianci.de.api.DEChannelSession;
import com.tianci.de.api.JsonParams;
import com.tianci.media.api.SkyMediaApiParam;
import com.tianci.media.base.SkyMediaItem;
import com.tianci.system.api.TCSystemService;
import com.tianci.system.data.SupportedHomepageXmlNode;
import com.tianci.system.data.TCEnumSetData;
import com.tianci.system.data.TCInfoSetData;
import com.tianci.system.data.TCSetData;
import com.tianci.system.define.SkyConfigDefs;
import com.tianci.system.define.TCEnvKey;
import com.tianci.user.api.bonuspoint.BonusPointParams;
import com.tianci.user.data.UserInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LiteCCConnectorServiceStub extends ILiteCCConnectorService.Stub implements
        SkyCmdProcessInstanceListener {
    private static final String TAG = LiteCCConnectorService.TAG;

    private static final String APP_SESSION = "tianci_appstore";
    private static final String DE_PKGNAME = "com.tianci.de";
    private static final String DE_APK_FILE = "SkyDEService.apk";
    private static final String DE_APK_FILE41 = "SkyDEService400.apk";
    private static final int DE_VERSION_CODE = 421000000;

    private SkyCmdConnectorListener listener = null;
    private SkyCmdProcessInstance cmdprocess = null;
    private Context mContext = null;
    private CoocaaVersion coocaaversion = null;
    private boolean bDestroyed = false;

    private String session = LiteCCConnector.ERRORCODE_SESSION_NOT_LOADED;

    private List<AIDLInterface<ILiteCCConnectorHandler>> handlers = new ArrayList<AIDLInterface<ILiteCCConnectorHandler>>();
    private String flag[] = {"true"};

    public LiteCCConnectorServiceStub(Context context) {
        bDestroyed = false;
        mContext = context;
        Intent intent = new Intent(LiteCCConnector.BROADCAST_CCC_ON_CONNECT_START_ACTION);
        try {
            coocaaversion = CoocaaApplication.getCoocaaVersion();
        } catch (Exception e1) {
        }
        LogUtils.d(TAG, "CoocaaVersion:" + coocaaversion);
        if (coocaaversion == null) {
            LogUtils.d(TAG, "init coocaasystem startCodeService");
            intent.putExtra(LiteCCConnector.BROADCAST_CCC_ON_CONNECT_START_EXTRA_VERSION, 3);
            startCodeService();// waibubanben(eg:xiaomi box tianci3.2)
            LiteHandlerThread.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    cmdprocess = SkyCmdProcessInstance.getCmdProcessInstance(mContext,
                            LiteCCConnectorServiceStub.this, mContext.getPackageName(),
                            mContext.getPackageName());
                }
            });
        } else if ((coocaaversion.major >= 4 && coocaaversion.minor >= 20)) {
            // coocaa system > 4.20
            LogUtils.d(TAG, "init coocaasystem update42");
            intent.putExtra(LiteCCConnector.BROADCAST_CCC_ON_CONNECT_START_EXTRA_VERSION, 2);
            update42DE();
            LiteHandlerThread.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    cmdprocess = SkyCmdProcessInstance.getCmdProcessInstance(mContext,
                            LiteCCConnectorServiceStub.this);
                }
            });
        } else if (coocaaversion.major == 4 && coocaaversion.minor < 20 && coocaaversion.minor >= 1) {
            // coocaa system 4.1*
            LogUtils.d(TAG, "init coocaasystem install41");
            intent.putExtra(LiteCCConnector.BROADCAST_CCC_ON_CONNECT_START_EXTRA_VERSION, 1);
            install41DE();
            LiteHandlerThread.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    cmdprocess = SkyCmdProcessInstance.getCmdProcessInstance(mContext,
                            LiteCCConnectorServiceStub.this);
                }
            });
        } else if (coocaaversion.major == 4 && coocaaversion.minor == 0) {
            LogUtils.d(TAG, "init coocaasystem fuck 4.0");
            // coocaa system 4.0 not support now!! because of deservice
            intent.putExtra(LiteCCConnector.BROADCAST_CCC_ON_CONNECT_START_EXTRA_VERSION, 0);
        } else if (coocaaversion.major >= 5) {
            LiteHandlerThread.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    cmdprocess = SkyCmdProcessInstance.getCmdProcessInstance(mContext,
                            LiteCCConnectorServiceStub.this);
                }
            });
        }
        mContext.sendBroadcast(intent);
    }

    @Override
    public ComponentName getCurrentLauncher() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("getCurrentLauncher begin waiting!");
                long waitTime = System.currentTimeMillis();
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                waitTime = System.currentTimeMillis() - waitTime;
                System.out.println("wait time :" + waitTime + ";" + flag);
            }
        }
        TCSetData tmpHomepagesetData = TCSystemService.getInstance().getSetData(
                TCEnvKey.SKY_SYSTEM_ENV_HOMEPAGE_SWITCH);
        if (tmpHomepagesetData != null) {
            TCEnumSetData enumSetData = (TCEnumSetData) tmpHomepagesetData;
            SupportedHomepageXmlNode currentNode = new SupportedHomepageXmlNode(
                    enumSetData.getCurrent());
            return new ComponentName(currentNode.pkgName, currentNode.clsName);
        }
        return new ComponentName("", "");
    }

    @Override
    public String getLocation() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("getLocation begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            TCInfoSetData data = (TCInfoSetData) TCSystemService.getInstance().getSetData(
                    TCEnvKey.SKY_SYSTEM_ENV_LOCATION);
            return data.getCurrent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String getStorage() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("getStorage begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        StringBuffer devices = new StringBuffer();
        try {
            ArrayList<String> diskByte = new ArrayList<String>();
            TCEnumSetData data = (TCEnumSetData) TCSystemService.getInstance()
                    .getSetData(SkyConfigDefs.SKY_CFG_DISKINFO_SETTING_EXCEPT_INTERNAL_SDCARD);
            if (null == data) {
                data = (TCEnumSetData) TCSystemService.getInstance().getSetData(
                        SkyConfigDefs.SKY_CFG_DISKINFO_SETTING);
            }
            if (data != null) {
                TCEnumSetData data2 = (TCEnumSetData) data;
                diskByte = (ArrayList<String>) data2.getEnumList();
            }
            LogUtils.i("", "sunny disk diskByte diskByte:" + diskByte);
            if (diskByte != null && diskByte.size() > 0) {
                for (int i = 0; i < diskByte.size(); i++) {
                    LogUtils.i("", "sunny disk diskByte diskByte2:" + diskByte);
                    String disk = diskByte.get(i);
                    if (disk != null) {
//                        devices.append("?");
                        devices.append(disk);
                    }
                    LogUtils.i("", "sunny disk getStorage:" + diskByte.size() + ";" + disk);
                }
                LogUtils.i("", "sunny disk getStorage:" + diskByte.size());
            }
            return devices.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String getServer() throws RemoteException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getUserSession() throws RemoteException {
        return session;
    }

    @Override
    public void sendCmd(String arg0, byte[] body) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("sendCmd begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            cmdprocess.sendCommand(listener, new SkyCmdURI(arg0), body);
        } catch (Exception e) {
        }
    }

    @Override
    public byte[] execCmd(String arg0, byte[] body) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("execCmd begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            return cmdprocess.execCommand(listener, new SkyCmdURI(arg0), body);
        } catch (Exception e) {
            return new byte[0];
        }
    }

    @Override
    public String readDEChannel(String arg0) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("readDEChannel begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            DEChannelSession session = DEChannelSession.fromSerialize(arg0);
            return CoocaaSystemApi.deApi.readDEChannel(session);
        } catch (Exception e) {
            return LiteCCConnector.ERRORCODE_READ_DECHANNEL_EMPTY;
        }
    }

    @Override
    public boolean writeDEChannel(String arg0) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("writeDEChannel begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            DEChannelSession session = DEChannelSession.fromSerialize(arg0);
            LogUtils.d(TAG, "writeDEChannel  ip:" + session.getAuthIP());
            CoocaaSystemApi.deApi.writeDEChannel(session);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean starQRCode() throws RemoteException {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.tianci.qrcode", "com.tianci.qrcode.SkyQrcode");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean startAppWithComponentName(ComponentName arg0) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startAppWithComponentName begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (CoocaaSystemApi.mediaApi != null) {
            SkyMediaApiParam param = new SkyMediaApiParam();
            param.setStartAppCaller(mContext.getPackageName(), true);
            param.setStartAppPackageName(arg0.getPackageName(), arg0.getClassName());
            LogUtils.i("PointResult", "startAppBonusPoints 0:" + arg0.getPackageName());
            startAppBonusPoints(arg0.getPackageName());
            CoocaaSystemApi.mediaApi.startApp(param);
            return true;
        }
        return false;
    }

    @Override
    public boolean startAppWithPackageName(String arg0) throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startAppWithPackageName begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (CoocaaSystemApi.mediaApi != null) {
            SkyMediaApiParam param = new SkyMediaApiParam();
            param.setStartAppCaller(mContext.getPackageName(), true);
            param.setStartAppPkgName(arg0);
            LogUtils.i("PointResult", "startAppBonusPoints 1:" + arg0);
            startAppBonusPoints(arg0);
            CoocaaSystemApi.mediaApi.startApp(param);
            return true;
        }
        return false;
    }

    @Override
    public boolean startDeviceInfo() throws RemoteException {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.tianci.systeminfo",
                    "com.tianci.systeminfo.SkySystemInfoActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean startMediaBrowser() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startMediaBrowser begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (coocaaversion.major >= 5) {
            try {
                Intent arg0 = new Intent();
                arg0.setClassName("com.tianci.localmedia", "com.tianci.localmedia.MainActivity");
                arg0.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(arg0);
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            try {
                SkyCmdURI cmdUrl;
                cmdUrl = new SkyCmdURI(TCUILogicUtil.getCmdheaderByModelscence(TCModelScence.MEDIA)
                        + TCMoviePageCmd.SHOW_LOCAL_MEDIA.toString());
                SkyData data = new SkyData();
                SkyApplication.getApplication().sendCommand(listener, cmdUrl, data.toBytes());
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @Override
    public boolean startMediaCenter() throws RemoteException {
        try {
            if (coocaaversion.major >= 5) {
                Intent intent = new Intent();
                intent.setClassName("com.tianci.movieplatform",
                        "com.tianci.movieplatform.MoviePlatformActivity");
                intent.putExtra("company", "voole");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } else {
                Intent intent = new Intent();
                intent.setClassName("com.tianci.movieplatform",
                        "com.tianci.movieplatform.MoviePlatformActivity");
                intent.putExtra("company", "voole");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean startNetSetting() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startNetSetting begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            SkyCmdURI cmdUrl = new SkyCmdURI(
                    TCUILogicUtil.getCmdheaderByModelscence(TCModelScence.NET)
                            + TCNetLogicCmd.SHOW_NET_OPEN.toString());
            SkyData data = new SkyData();
            SkyApplication.getApplication().sendCommand(listener, cmdUrl, data.toBytes());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean startSourceSwitch() throws RemoteException {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startSourceSwitch begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (coocaaversion.major >= 5) {
            try {
                Intent intent = new Intent("startSourceList");
                intent.putExtra("specialKey", SkyworthBroadcastKey.SKY_BROADCAST_KEY_SIGNAL);
                mContext.sendBroadcast(intent);
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            if (CoocaaSystemApi.deApi == null)
                return false;
            CoocaaSystemApi.deApi.onKeyDown(SkyworthKey.SKY_KEY_TV_INPUT.toString());
            return true;
        }
    }

    @Override
    public boolean startSystemUpgrade() throws RemoteException {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.tianci.loader",
                    "com.tianci.loader.loaderservice.TvosLoaderServiceActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean startTVSetting() throws RemoteException {
        if (coocaaversion.major >= 5) {
            try {
                Intent mIntent = new Intent();
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.setClassName("com.tianci.setting", "com.tianci.setting.TianciSetting");
                mContext.startActivity(mIntent);
                return true;
            } catch (Exception e) {
                return false;
            }

        } else {
            synchronized (flag) {
                while (!flag[0].equals("false")) {
                    System.out.println("startTVSetting begin waiting!");
                    try {
                        flag.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            SkyCmdURI cmdUrl;
            try {
                cmdUrl = new SkyCmdURI(TCUILogicUtil.cmdHeaderSys
                        + TCUiLogicCmd.TC_UILOGIC_CMD_SHOW_SHOTCUT.toString());
                LogUtils.d("----------", cmdUrl.getCmdPackage() + " " + cmdUrl.getTargetClassName());
                SkyApplication.getApplication().sendCommand(listener, cmdUrl,
                        "SKY_CFG_TV_SETTING".getBytes());
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @Override
    public boolean startPlayer(String name, String url, boolean needHistory) {
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startPlayer begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.d("play", "startPlayer  name:" + name + " url:" + url);
        SkyMediaItem item = new SkyMediaItem();
        item.type = SkyMediaItem.SkyMediaType.MOVIE;
        item.name = name;
        item.url = url;
        item.extra.put("needParse", "false");
        if (needHistory)
            item.extra.put("need_history", "true");
        else
            item.extra.put("need_history", "false");
        SkyMediaItem[] items = new SkyMediaItem[]{item};
//        CoocaaSystemApi.mediaApi.startPlayer(items, 0);
        SkyMediaApiParam param = new SkyMediaApiParam();
        param.setPlayList(items, 0);
        CoocaaSystemApi.mediaApi.startPlayerCompatibilityAllVersion(param);
        return true;
    }

    @Override
    public boolean startGuide() {
        try {
            Intent intent = new Intent();
            intent.setAction("coocaa.intent.GUIDE");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public synchronized boolean showConnectNetworkDialogWithConfirmUI() {
        if (CoocaaSystemApi.settingApi.isFirstTimeRunApp(mContext)) {
            CoocaaSystemApi.settingApi.clearFirstTimeRunApp(mContext);
            return CoocaaSystemApi.settingApi.connectNetworkWithConfirmUI(mContext);
        }
        return false;
    }

    @Override
    public void firstStartAppPoints(String tag) {//第一次进入App
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("firstStartAppPoints begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.i("PointResult", "sunny point firstStartAppPoints:" + tag);
        BonusPointParams params = new BonusPointParams();
        params.memo = "首次进入应用";
        params.itemsTag = tag;
        CoocaaSystemApi.pointApi.add(params);
    }

    @Override
    public void startAppBonusPoints(String pkg) {//打开APP获得积分
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startPlayer begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (pkg.equals("com.tianci.appstore") || pkg.equals("com.coocaa.x.app.hall"))
            return;
        LogUtils.i("PointResult", "sunny point  startAppBonusPoints:" + pkg);
        BonusPointParams params = new BonusPointParams();
        params.itemData = pkg; // package name?
        params.memo = "打开第三方应用";
        params.itemsTag = "OTHER_APP_OPEN";
        CoocaaSystemApi.pointApi.add(params);
    }

    @Override
    public void installAppPoints(String pkg) {//安装APP获得积分
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startPlayer begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.i("PointResult", "sunny point  installAppPoints:" + pkg);
        BonusPointParams params = new BonusPointParams();
        params.itemData = pkg; // package name?
        params.memo = "安装应用";
        params.itemsTag = "APP_DOWNLOAD_INSTALL";
        CoocaaSystemApi.pointApi.add(params);
    }

    @Override
    public void startVideoPoints(String url) {//打开影视积分
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startVideoPoints begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.i("PointResult", "sunny point  startVideoPoints:" + url);
        BonusPointParams params = new BonusPointParams();
        params.itemData = "VIDEO";
        params.itemData1 = url;
        params.memo = "打开影视";
        params.itemsTag = "OPERATION_OPEN";
        CoocaaSystemApi.pointApi.add(params);
    }

    @Override
    public void startWebPoints(String url) {//打开图片或网页积分
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("startWebPoints begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.i("PointResult", "sunny point  startWebPoints:" + url);
        BonusPointParams params = new BonusPointParams();
        params.itemData = "WEB";
        params.itemData1 = url;
        params.memo = "打开网页";
        params.itemsTag = "OPERATION_OPEN";
        CoocaaSystemApi.pointApi.add(params);
    }

    @Override
    public String getCurUserPoints() {//获取当前用户
        synchronized (flag) {
            while (!flag[0].equals("false")) {
                System.out.println("getCurUserPoints begin waiting!");
                try {
                    flag.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        UserInfo userInfo = (UserInfo) CoocaaSystemApi.userApi.getCurUserInfo();
        String userId = userInfo.userId;
        return userId;
    }

    @Override
    public byte[] onHandler(final String fromtarget, final String cmd, final byte[] body) {
        String _body = null;
        try {
            _body = String.valueOf(body);
        } catch (Exception e1) {
        }
        LogUtils.d(TAG, "onHandler from:" + fromtarget + "  cmd:" + cmd + "   body:" + _body);
        if (cmd.equals(DEDefine.CmdEnum.CMD_DESERVICE_BOOTCOMPLATE.toString()))
            registerDE();
        synchronized (handlers) {
            for (final AIDLInterface<ILiteCCConnectorHandler> i : handlers) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            i.i.onHandler(fromtarget, cmd, body);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        return null;// SkyObjectByteSerialzie.toBytes(Boolean.TRUE.toString());
    }

    @Override
    public void onResult(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub

    }

    @Override
    public String getCmdClassName() {
        return getClass().getName();
    }

    @Override
    public byte[] requestPause(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public byte[] requestResume(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public byte[] requestRelease(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public byte[] requestStartToVisible(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public byte[] requestStartToForground(String fromtarget, String cmd, byte[] body) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCmdConnectorInit() {
        CoocaaApplication.post(new Runnable() {
            private String getSession() {
                String session = null;
                int count = 0;
                // delay 5s to getUserSession
                while (count < 500 && ((session = CoocaaSystemApi.userApi.getSession()) == null)) {
                    try {
                        Thread.sleep(10);
                        count++;
                    } catch (InterruptedException e) {
                    }
                }
                if (session != null)
                    return session;
                return LiteCCConnector.ERRORCODE_SESSION_NOT_EXIST;
            }

            @Override
            public void run() {
                LogUtils.d(TAG, "#####################onCmdConnectorInit");
                listener = cmdprocess.getCmdConnectorListener();
                CoocaaSystemApi.create(listener);
                if (isCoocaaSystem()) {
                    session = getSession();
                    Intent intent = new Intent(
                            LiteCCConnector.BROADCAST_CCC_ON_SESSION_UPDATE_ACTION);
                    intent.putExtra(LiteCCConnector.BROADCAST_CCC_ON_SESSION_UPDATE_EXTRA_SESSION,
                            session);
                    mContext.sendBroadcast(intent);
                } else
                    session = LiteCCConnector.ERRORCODE_SESSION_NOT_EXIST;
                LogUtils.i(TAG, "get session:" + session);
                registerDE();
                mContext.sendBroadcast(new Intent(
                        LiteCCConnector.BROADCAST_CCC_ON_CONNECT_COMPLETE_ACTION));
                synchronized (flag) {
                    flag[0] = "false";
                    flag.notifyAll();
                    LogUtils.d("wait", "onCmdConnectorInit  wait notifyAll" + flag[0]);
                }
            }
        });
    }

    private void registerDE() {
        JsonParams parma = new JsonParams(APP_SESSION, null, null, null);
        DEChannelSession session = new DEChannelSession(parma);
        boolean success = CoocaaSystemApi.deApi.registerDEChannelSession(session);
        if (success)
            LogUtils.d(TAG, APP_SESSION + " register de channel success!!");
        else
            LogUtils.d(TAG, APP_SESSION + " register de channel failed!!");
    }

    private boolean isCoocaaSystem() {
        if (coocaaversion != null && coocaaversion.major >= 4)// && !isA55())
            return true;
        return false;
    }

    private int getDEVersionCode() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(DE_PKGNAME, 0);
            if (info != null)
                return info.versionCode;
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    private void startCodeService() {
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                CoocaaDEConnecter.connecter.bindService(mContext, mContext.getPackageName());
                CoocaaIPCConnecter.connecter.bindService(mContext, mContext.getPackageName());
            }
        });
    }

    private void stopCodeService() {
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                CoocaaDEConnecter.connecter.unbindService(mContext);
                CoocaaIPCConnecter.connecter.unbindService(mContext);
            }
        });
    }

    private void install41DE() {
        int vc = getDEVersionCode();
        LogUtils.i(TAG, "install41DE() internal de versioncode:" + vc + "  target mini version code:"
                + DE_VERSION_CODE);
        if (vc < DE_VERSION_CODE) {
            installApk(DE_APK_FILE41);
            mContext.startService(new Intent("com.tianci.de"));
        }
    }

    private void update42DE() {
        int vc = getDEVersionCode();
        if (isAXX())
            return;
        LogUtils.i(TAG, "update42DE() internal de versioncode:" + vc + "  target mini version code:"
                + DE_VERSION_CODE);
        if (vc < DE_VERSION_CODE && vc > 0) {
            installApk(DE_APK_FILE);
            mContext.startService(new Intent("com.tianci.de"));
        }
    }

    private void installApk(String file) {
        try {
            String path = mContext.getDir("coocaa_apk", Context.MODE_PRIVATE).getAbsolutePath()
                    + "/" + "coocaa.apk";
            InputStream is = mContext.getResources().getAssets().open(file);
            FileOutputStream fs = new FileOutputStream(path);
            byte[] buffer = new byte[4096];
            int byteread;
            while ((byteread = is.read(buffer)) != -1)
                fs.write(buffer, 0, byteread);
            is.close();
            fs.close();
            try {
                Runtime.getRuntime().exec("chmod 777 " + path);
            } catch (Exception e) {
                e.printStackTrace();
            }
            StringBuilder command = new StringBuilder().append("pm install -r ").append(path);
            CommandResult commandResult = ShellUtils.execCommand(command.toString(), true, true);
            if (commandResult.successMsg != null
                    && (commandResult.successMsg.contains("Success") || commandResult.successMsg
                    .contains("success"))) {// success
                LogUtils.d(TAG, "***************   " + file + "  install done");
            } else {// fail
                LogUtils.d(TAG, "***************   " + file + "  install failed");
            }
            File f = new File(path);
            if (f.exists())
                f.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isAXX() {
        return CoocaaOSTypeChecker.isMixedCoocaaOSType();
        // String model = SystemProperties.get("ro.product.model");
        // if (model != null)
        // {
        // model = model.toLowerCase();
        // return model.contains("a43") || model.contains("a55");
        // }
        // return false;
    }

    @Override
    public void addHandler(ILiteCCConnectorHandler arg0) throws RemoteException {
        synchronized (handlers) {
            if (arg0 != null) {
                IBinder binder = arg0.asBinder();
                for (AIDLInterface<ILiteCCConnectorHandler> i : handlers) {
                    if (i.binder == binder)
                        return;
                }
                AIDLInterface<ILiteCCConnectorHandler> i = new AIDLInterface<ILiteCCConnectorHandler>(
                        binder, arg0);
                handlers.add(i);
            }
        }
    }

    @Override
    public void removeHandler(ILiteCCConnectorHandler arg0) throws RemoteException {
        synchronized (handlers) {
            if (listener != null) {
                IBinder binder = arg0.asBinder();
                for (AIDLInterface<ILiteCCConnectorHandler> i : handlers) {
                    if (i.binder == binder) {
                        handlers.remove(i);
                        LogUtils.i("PointResult", "sunny onHandler remove:" + binder);
                        break;
                    }
                }
            }
        }
    }


    @Override
    public boolean collectSpecialpAppStart(String pkgName, String bussiness_type, String mapJson) {
        HashMap<String, String> map = JSONObject.parseObject(mapJson, HashMap.class);
        while (TCSystemService.getInstance() == null)
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//        return TCSystemService.getInstance().collectSpecialpAppStart(pkgName, bussiness_type, map);
        return true;
    }


    public void destroy() {
        synchronized (this) {
            if (bDestroyed)
                return;
            bDestroyed = false;
            cmdprocess.onDestory();
            if (coocaaversion == null) {
                stopCodeService();// waibubanben(eg:xiaomi box tianci3.2)
            }
        }
    }

    @Override
    public void whoAmI() {
        LogUtils.d("wai", "<<LiteCCConnectorService>> who am i??  " + mContext.getPackageName());
    }
}
